﻿using Gma.System.MouseKeyHook;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mousetouchhookwinform
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            Subscribe();
            GetSysProcessWithWindow();//获取当前的所有的窗口，且有名称的窗口

        }
        private IKeyboardMouseEvents m_GlobalHook;//钩子
        //获取当前所有窗口的进程，用于鼠标钩子使用
        List<Process> processWithWindow = new List<Process>();
        private void GetSysProcessWithWindow()
        {
            Process[] processes = Process.GetProcesses();
            processWithWindow.Clear();
            foreach (var p in processes)
            {
                if (p.MainWindowHandle == IntPtr.Zero) continue;
                if (p.MainWindowTitle.Length == 0) continue;
                processWithWindow.Add(p);
            }
        }
        public void Subscribe()
        {
            m_GlobalHook = Hook.GlobalEvents();
            m_GlobalHook.MouseDownExt += M_GlobalHook_MouseDownExt;
            m_GlobalHook.MouseMoveExt += M_GlobalHook_MouseMoveExt;
            m_GlobalHook.MouseDown += M_GlobalHook_MouseDown;
        }
        [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]
        public static extern IntPtr WindowFromPoint(int xPoint,int yPoint);
        private void M_GlobalHook_MouseMoveExt(object sender, MouseEventArgs e)
        {
            var handle = WindowFromPoint(e.X, e.Y);//鼠标移动到的进程
            foreach (var p in processWithWindow)
            {
                if (p.MainWindowHandle == handle)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append($"名称:{p.MainModule.FileVersionInfo.ProductName}{Environment.NewLine}");
                    stringBuilder.Append($"版本:{p.MainModule.FileVersionInfo.FileVersion}{Environment.NewLine}");
                    stringBuilder.Append($"描述:{p.MainModule.FileVersionInfo.FileDescription}{Environment.NewLine}");
                    label1.Text = stringBuilder.ToString();
                    break;
                }
            }
        }

        //鼠标按钮下的事件处理器
        private void M_GlobalHook_MouseDownExt(object sender, MouseEventArgs e)
        {          
            if (e.Button == MouseButtons.Right)
            {
                m_GlobalHook.MouseDownExt -= M_GlobalHook_MouseDownExt;
                m_GlobalHook.MouseMoveExt -= M_GlobalHook_MouseMoveExt;
                m_GlobalHook.MouseDown -= M_GlobalHook_MouseDown;
                m_GlobalHook.Dispose();
            }
        }

        private void M_GlobalHook_MouseDown(object sender, MouseEventArgs e)
        {
            MessageBox.Show("鼠标按下去了");
        }


    }
}
